import json

from django.utils.deprecation import MiddlewareMixin


class MyMiddleware(MiddlewareMixin):

    def process_response(self, request, response):
        res = json.loads(response.content)
        if res.get('code') == 200:
            # 获取返回数据
            data = res.get('data')
            # http请求返回数据
            for key, value in data.items():
                if isinstance(value, dict) or isinstance(value, str):
                    response.content = json.dumps({
                        'code': res.get('code'),
                        'message': res.get('message'),
                        'data': self.remove_nulls(res.get('data'))
                    }, ensure_ascii=False)
                    return response
            # sql语句返回数据
            total = 0
            items = len(data)
            for key, value in data.items():
                total += len(value)
            if total > 30:
                for key, value in data.items():
                    data[key] = value[:int(30/items)]
                    res['message'] = "数据过长，仅展示部分数据。"
            if res.get('code') == 200:
                response.content = json.dumps({
                    'code': res.get('code'),
                    'message': res.get('message'),
                    'data': self.remove_nulls(data)
                }, ensure_ascii=False)
        return response

    def remove_nulls(self, data):
        if isinstance(data, dict):
            return {k: self.remove_nulls(v) for k, v in data.items() if v is not None}
        elif isinstance(data, list):
            return [self.remove_nulls(item) for item in data]
        else:
            return data
